import { has, eq } from 'lodash'
import { State } from 'vuex-class'
import { Vue, Component } from 'vue-property-decorator'

import { OperateRel, Rel } from '@/types/operate-rel'
import { UserAuth } from '@/types/user.state'

const rels: OperateRel = {
  Index: [
    { action: 'project_create', control: '/project/create' },
    { action: 'project_edit', control: '/project/edit' },
    { action: 'project_delete', control: '/project/delete' },
    { action: 'project_list', control: '/project/list' }
  ]
}

interface Action {
  [propName: string]: boolean
}

@Component
export default class PermissionMixin extends Vue {
  @State('auth', { namespace: 'user' })
  readonly userAuth!: UserAuth

  private permission: Action = {}

  created () {
    this.permission = this.getActions(this.$options.name || '')
  }

  getActions (name: string): Action {
    if (!name) {
      return {}
    }
    if (has(rels, name)) {
      const ops: Rel[] = rels[name]
      const actions: Action = {}
      ops.forEach((value: Rel) => {
        actions[value.action] = eq(process.env.permission, 'on') || this.userAuth.operations.includes(value.control)
      })
      return actions
    }
    return {}
  }
}
